package ai.esc.speedy.admin.user.interfaces.controller;

import ai.esc.speedy.admin.user.api.*;
import ai.esc.speedy.admin.user.domain.valueobject.SimplePage;
import ai.esc.speedy.admin.user.domain.valueobject.SpeedyAppUserData;
import ai.esc.speedy.common.base.BaseController;
import ai.esc.speedy.common.base.Message;
import ai.esc.speedy.common.util.SageStrUtil;
import com.alibaba.fastjson.JSON;
import org.axonframework.messaging.responsetypes.ResponseTypes;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * App用户接口
 *
 * @author Rubin
 * @version v1 2020/3/3 17:11
 */
@RestController
@RequestMapping("/user")
public class AppUserController extends BaseController {

    /**
     * 校验邮箱或手机号有没有被注册
     *
     * @param account
     * @return
     */
    @GetMapping("/login/check/account/{account}")
    public Message checkAccountIsExist(@PathVariable String account) {
        return Message.builder().ok()
                .data(queryGateway.query(
                        new CheckAccountQuery(account), Boolean.class).join())
                .build();
    }

    /**
     * 发送验证码
     *
     * @param phoneOrEmail
     * @return
     */
    @GetMapping("/login/v_code/{phoneOrEmail}")
    public Message sendVerificationCode(@PathVariable String phoneOrEmail) {
        return Message.builder().ok()
                .data(queryGateway.query(
                        phoneOrEmail.contains("@") ? new EmailVerificationCodeQuery(phoneOrEmail) :
                                new SmsVerificationCodeQuery(phoneOrEmail), String.class).join())
                .build();
    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @return
     */
    @GetMapping("/login/check/v_code/{phone}/{code}")
    public Message checkVerificationCode(@PathVariable String phone, @PathVariable String code) {
        return Message.builder().ok()
                .data(queryGateway.query(
                        new CheckVerificationCodeQuery(phone, code), Boolean.class).join())
                .build();
    }

    /**
     * 下发动态加密码
     *
     * @return
     */
    @GetMapping("/login/dynamic_e_code/{identification}")
    public Message sendDynamicEncryptionCode(@PathVariable String identification) {
        return Message.builder().ok()
                .data(queryGateway.query(
                        new DynamicEncryptionCodeQuery(identification), String.class).join())
                .build();
    }

    /**
     * 注册
     *
     * @param appId
     * @param username           phone、Email
     * @param encryptionPassword
     * @return
     */
    @PostMapping("/register/{appId}/{username}")
    public Message register(@PathVariable String appId,
                            @PathVariable String username,
                            @RequestBody String encryptionPassword) {
        SpeedyAppUserData userData = new SpeedyAppUserData();
        userData.setName(SageStrUtil.keepAndOmit(username));
        userData.setEmail(username.contains("@") ? username : "");
        userData.setPhone(!username.contains("@") ? username : "");

        return Message.builder().ok()
                .data(commandGateway.send(new CreateAppUserCommand(uidGenerator.getIdStr(), appId,
                        JSON.parseObject(JSON.toJSONString(userData)), encryptionPassword, username)).join())
                .build();
    }

    /**
     * 一键登录
     * <p>
     * 当作查询命令处理，如果未查到，发送一条注册命令。
     *
     * @param username        手机号或邮箱
     * @param identifyingCode 验证码
     * @return token
     */
    @PostMapping("/login/{username}/{identifyingCode}")
    public Message loginOrRegister(@PathVariable String username,
                                   @PathVariable String identifyingCode) {
        return Message.builder().ok()
                .data(queryGateway.query(
                        new LoginQuery("speedy", username, identifyingCode), AppUserTokenResponse.class).join())
                .build();
    }

    /**
     * 手机+密码登录
     *
     * @param query
     * @return token
     */
    @PostMapping("/login/password")
    public Message loginByPassword(@RequestBody LoginQuery query) {
        String encryptionPassword = query.getPassword();

        // 解密...


        return Message.builder().ok()
                .data(queryGateway.query(
                        new LoginQuery(query.getAppId(), query.getUsername(), encryptionPassword), Map.class).join())
                .build();
    }

    /**
     * 第三方登录
     *
     * @param type 第三方类型
     * @return
     */
    @PostMapping("/login/third/{type}")
    public Message thirdPartyLogin(@PathVariable String type) {
        return Message.builder().ok()
                .data(queryGateway.query(
                        new ThirdPartyLoginQuery(type), AppUserTokenResponse.class).join())
                .build();
    }

    /**
     * 查询用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/info")
    public Message appUserInfo(HttpServletRequest request) {
        Enumeration<String> authorization = request.getHeaders("Authorization");
        return Message.builder().ok()
                .data(queryGateway.query(
                        new AppUserInfoQuery("authorization.nextElement()"), SpeedyAppUserData.class).join())
                .build();
    }

    /**
     * 获取用户列表
     *
     * @param offset 第几页
     * @param limit  每页显示数
     * @return 分页列表
     */
    @GetMapping("/list/{offset}/{limit}")
    public Message getAppUserList(@PathVariable int offset, @PathVariable int limit) {
        return Message.builder().ok()
                .data(queryGateway.query(
                        new AppUserListQuery(offset, limit),
                        ResponseTypes.instanceOf(SimplePage.class)).join())
                .build();
    }

    /**
     * 更新用户信息
     *
     * @param userId
     * @param userData
     * @return
     */
    @PostMapping("/change/data/{userId}")
    public Message updateAppUserData(@PathVariable String userId,
                                     @RequestBody SpeedyAppUserData userData) {
        return Message.builder().ok()
                .data(commandGateway.send(
                        new UpdateAppUserDataCommand(userId,
                                JSON.parseObject(JSON.toJSONString(userData)))
                ).join())
                .build();
    }

    /**
     * 切换用户身份
     *
     * @param userId
     * @param status
     * @return
     */
    @PostMapping("/switch/identity/{userId}")
    public Message switchUserIdentity(@PathVariable String userId,
                                      @RequestBody int status) {
        return Message.builder().ok()
                .data(commandGateway.send(
                        new UpdateAppUserStatusCommand(userId, status)).join())
                .build();
    }

    /**
     * 修改用户密码
     *
     * @param userId
     * @param password
     * @return
     */
    @PostMapping("/change/password/{userId}")
    public Message changeAppUserPassword(@PathVariable String userId,
                                         @RequestBody String password) {
        return Message.builder().ok()
                .data(commandGateway.send(
                        new UpdateAppUserPasswordCommand(userId, password)).join())
                .build();
    }


    @PostMapping("/test")
    public Message test() {


        return Message.builder().ok()
                .build();
    }


}
